import {
  SET_FRM_PALLET_LIST,
  SET_FRM_PALLET_ORDER_LIST,
  SET_FRM_PALLET_CURRENT_ORDER,
  SET_FRM_PALLET_ORDER_LINES,
  SET_FRM_PALLET_ITEM_DETAILS,
  SET_FRM_PALLET_BARCODE_DETAILS,
  SET_FRM_PALLET_OPS_FORM,
  DEL_FRM_PALLET_BARCODE,
  CLEAR_FRM_PALLET_OPS_FORM,
  SET_FRM_PALLET_ORDER_LINE,
} from "./action-types";

const initialState = {
  currentPallet: null,
  currentOrder: null,

  palletList: [],
  palletListOffset: 0,

  orderList: [],
  orderListOffset: 0,

  orderLines: [],
  orderLineOffset: 0,

  palletOrderLine: null,

  opsFormData: null,

  itemDetails: [],
  barcodeDetails: [],
};

const handlePalletList = (state, payload) => {
  let { items, offset } = payload;
  if (items.length === 0 && offset === 0) {
    return { ...state, palletList: [], palletListOffset: 0 };
  } else {
    return {
      ...state,
      palletList: state.palletList.concat(items),
      palletListOffset: offset,
    };
  }
};

const handleOrderList = (state, payload) => {
  let { items, offset } = payload;
  if (items.length === 0 && offset === 0) {
    return { ...state, orderList: [], orderListOffset: 0 };
  } else {
    return {
      ...state,
      orderList: state.orderList.concat(items),
      orderListOffset: offset
    };
  }
};

const handleOrderLines = (state, payload) => {
  let { items, offset } = payload;
  if (items.length === 0 && offset === 0) {
    return { ...state, orderLines: [], orderLineOffset: 0 };
  } else {
    return {
      ...state,
      orderLines: state.orderLines.concat(items),
      orderLineOffset: offset
    };
  }
};

const handleDelBarcode = (state, payload) => {
  return {
    ...state,
    barcodeDetails: state.barcodeDetails.filter((i) => i.id !== payload.id),
  };
};

const data = (state = initialState, action) => {
  switch (action.type) {
    case SET_FRM_PALLET_LIST:
      return handlePalletList(state, action.payload);
    case SET_FRM_PALLET_ORDER_LIST:
      return handleOrderList(state, action.payload);
    case SET_FRM_PALLET_CURRENT_ORDER:
      return { ...state, currentOrder: action.payload };
    case SET_FRM_PALLET_ORDER_LINES:
      return handleOrderLines(state, action.payload);
    case SET_FRM_PALLET_ITEM_DETAILS:
      return { ...state, itemDetails: action.payload.items };
    case SET_FRM_PALLET_BARCODE_DETAILS:
      return { ...state, barcodeDetails: action.payload.items };
    case SET_FRM_PALLET_OPS_FORM:
      return { ...state, opsFormData: action.payload };
    case DEL_FRM_PALLET_BARCODE:
      return handleDelBarcode(state, action.payload);
    case CLEAR_FRM_PALLET_OPS_FORM:
      return { ...state, opsFormData: null };
    case SET_FRM_PALLET_ORDER_LINE:
      return { ...state, palletOrderLine: action.payload.item };
    default:
      return state;
  }
};

export default data;
